package com.ytjj.qmyx.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Maps;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.enums.PlatformEnum;
import com.ytjj.common.model.FileResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.AliyunOSSClientUtil;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.enums.WxComplaintsStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.WxComplaintsCallBackRequest;
import com.ytjj.qmyx.mall.model.WxComplaintsReplyRequest;
import com.ytjj.qmyx.mall.model.response.WxComplaintsCallBackResponse;
import com.ytjj.qmyx.mall.service.ComplaintsService;
import com.ytjj.qmyx.mall.utils.WxPayServiceUtil;
import com.ytjj.qmyx.mall.utils.WxpayV3Util;
import joptsimple.internal.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RefreshScope
public class ComplaintsServiceImpl implements ComplaintsService {

    private static final String COMPLAINTS_URL = "/v3/merchant-service/complaints-v2";

    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private WxComplaintsMsgMapper wxComplaintsMsgMapper;
    @Resource
    private ComplaintsRecordsMapper complaintsRecordsMapper;
    @Resource
    private WxComplaintsHistoryMapper wxComplaintsHistoryMapper;
    @Resource
    private ComplaintsErrorRecordsMapper complaintsErrorRecordsMapper;
    @Resource
    private PayConfigMapper payConfigMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 投诉单自动回复内容
     */
    @Value("${auto.reply.content:您的投诉已由我们商城客服受理，后续将通过电话/微信处理您的问题，您也可以主动拨打我们的官方客服热线0000001706联系我们（上班时间: 9:00-12:00,13:30-18:30)，我们将竭诚为您服务}")
    private String autoReplyContent;

    @Value("${auto.reply.content2:您反馈的问题已记录，后续会有商城客服专员电话或微信联系您，请您务必保持通讯畅通，以便及时处理您的问题！您也可以在商城上班时间段（9:00-12:00，13:45-18:30）主动拨打客服热线0000001727，我们一定会竭诚为您服务！}")
    private String autoReplyContent2;

    @Override
    public String complaintsImagesUpLoad(String  fileUrl, String complaintId) throws Exception {

        Integer mchId = complaintsRecordsMapper.getMchIdByComplaintId(complaintId);
        PayConfig payConfig = payConfigMapper.selectByPrimaryKey(mchId);
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String result = WxpayV3Util.uploadImg(wxPayService.getConfig(), fileUrl);
        String returnUrl = Strings.EMPTY;
        if (StringUtils.isNotBlank(result)) {
            result = result.replaceAll("[\\\\]", "");
            Map map = JSONUtil.toBean(result, Map.class);
             returnUrl = Optional.ofNullable(String.valueOf(map.get("media_id"))).get();

        }
        return returnUrl;
    }

    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JSONObject queryComplaintsV3(String complaintId) throws Exception{
        Integer mchId = complaintsRecordsMapper.getMchIdByComplaintId(complaintId);
        PayConfig payConfig = payConfigMapper.selectByPrimaryKey(mchId);
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String url = COMPLAINTS_URL + "/" + complaintId;
        log.info("查询微信投诉详情参数:{}",url);
        JSONObject jsonObject = WxpayV3Util.queryComplaintsV3(url, wxPayService.getConfig());
        log.info("查询微信投诉详情返回:{}",jsonObject.toJSONString());
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ComplaintsHistoryResponse> wxComplaintsV3History(String complaintId) throws Exception{
        Integer mchId = complaintsRecordsMapper.getMchIdByComplaintId(complaintId);
        PayConfig payConfig = payConfigMapper.selectByPrimaryKey(mchId);
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String url = COMPLAINTS_URL + "/" + complaintId+"/negotiation-historys";
        log.info("查询微信投诉单协商历史参数:{}",url);
        JSONObject jsonObject = WxpayV3Util.queryComplaintsV3(url, wxPayService.getConfig());
        log.info("查询微信投诉单协商历史返回:{}",jsonObject.toJSONString());
        JSONArray data = jsonObject.getJSONArray("data");

        List<ComplaintsHistoryResponse> complaintsHistoryResponses = JSONArray.parseArray(data.toJSONString(), ComplaintsHistoryResponse.class);
        if (!CollectionUtils.isEmpty(complaintsHistoryResponses)) {
            List<String> logIds = complaintsHistoryResponses.stream().filter(item -> item.getLog_id() != null).map(ComplaintsHistoryResponse::getLog_id).collect(Collectors.toList());
            List<WxComplaintsHistory> wxComplaintsHistories = wxComplaintsHistoryMapper.queryByLogIds(logIds);
            for (ComplaintsHistoryResponse complaintsHistoryRespons : complaintsHistoryResponses) {
                if (!CollectionUtils.isEmpty(wxComplaintsHistories)) {
                    List<WxComplaintsHistory> collect = wxComplaintsHistories.stream().filter(item -> complaintsHistoryRespons.getLog_id().equals(item.getLogId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect) ) {
                        if (StringUtils.isNotBlank(collect.get(0).getMediaUrl())) {
                            String[] split = collect.get(0).getMediaUrl().split(",");
                            List<String> media_url = Arrays.asList(split);
                            if (complaintsHistoryRespons.getComplaint_media_list() !=null) {
                                complaintsHistoryRespons.getComplaint_media_list().setMedia_url(media_url);
                            }
                        }
                    } else {
                        List<String>  media_url = saveComplaintsHistory(complaintId, complaintsHistoryRespons, wxPayService.getConfig());
                        if (complaintsHistoryRespons.getComplaint_media_list() !=null) {
                            complaintsHistoryRespons.getComplaint_media_list().setMedia_url(media_url);
                        }
                    }
                } else {
                    List<String>  media_url = saveComplaintsHistory(complaintId, complaintsHistoryRespons, wxPayService.getConfig());
                    if (complaintsHistoryRespons.getComplaint_media_list() !=null) {
                        complaintsHistoryRespons.getComplaint_media_list().setMedia_url(media_url);
                    }

                }
            }
        }
        return complaintsHistoryResponses;
    }

    public List<String>  saveComplaintsHistory(String complaint_id, ComplaintsHistoryResponse complaintsHistoryResponse, WxPayConfig wxPayConfig) throws WxPayException{
        List<String> returnUrl = null;
        WxComplaintsHistory wxComplaintsHistory = new WxComplaintsHistory();
        wxComplaintsHistory.setLogId(complaintsHistoryResponse.getLog_id());
        wxComplaintsHistory.setOperatorAdminId(1);
        wxComplaintsHistory.setOperatorTime(complaintsHistoryResponse.getOperate_time());
        wxComplaintsHistory.setComplaintId(complaint_id);
        wxComplaintsHistory.setOperateDetails(complaintsHistoryResponse.getOperate_details());

        if (complaintsHistoryResponse.getComplaint_media_list() !=null && !CollectionUtils.isEmpty(complaintsHistoryResponse.getComplaint_media_list().getMedia_url())) {
             returnUrl = downLoadComplaintsHistoryImg(complaintsHistoryResponse.getComplaint_media_list().getMedia_url(), wxPayConfig);
            wxComplaintsHistory.setMediaUrl(returnUrl.stream().collect(Collectors.joining(",")));
        }

        wxComplaintsHistoryMapper.insert(wxComplaintsHistory);
        return  returnUrl;
    }


    public Integer  saveComplaintsHistory(String complaint_id,String logId,String operate_details,List<String> mediaUrl,Integer adminId) {
        WxComplaintsHistory wxComplaintsHistory = new WxComplaintsHistory();
        wxComplaintsHistory.setLogId(logId);
        wxComplaintsHistory.setOperatorAdminId(adminId);
        wxComplaintsHistory.setOperatorTime(new Date());
        wxComplaintsHistory.setComplaintId(complaint_id);
        wxComplaintsHistory.setOperateDetails(operate_details);
        if (!CollectionUtils.isEmpty(mediaUrl)) {
            wxComplaintsHistory.setMediaUrl(mediaUrl.stream().collect(Collectors.joining(",")));
        }
        return wxComplaintsHistoryMapper.insert(wxComplaintsHistory);
    }

    @Override
    public List<String> downLoadComplaintsHistoryImg(List<String> media_url, WxPayConfig wxPayConfig) throws WxPayException {
        List<String> returnUrl = new ArrayList<>();
        for (String url : media_url) {
            String urlStr = WxpayV3Util.downLoadComplaintsHistoryImg(url, wxPayConfig);
            returnUrl.add(urlStr);
        }
       return returnUrl ;
    }

    @Override
    public JSONObject wxComplaintsV3Complete(String complaintId,Integer adminId) throws Exception {
        Integer mchId = complaintsRecordsMapper.getMchIdByComplaintId(complaintId);
        PayConfig payConfig = payConfigMapper.selectByPrimaryKey(mchId);
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String url = COMPLAINTS_URL + "/" + complaintId+"/complete";
        JSONObject requestJsonObject = new JSONObject();
        requestJsonObject.put("complainted_mchid",payConfig.getMchId());
        log.info("查询微信投诉单反馈处理完成参数:{}",url);
        JSONObject jsonObject = WxpayV3Util.operationComplaintsV3(url, requestJsonObject,wxPayService.getConfig(),"post");
//        log.info("查询微信投诉单反馈处理完成返回:{}",jsonObject.toJSONString());

        return jsonObject;
    }

    @Override
    public JSONObject wxComplaintsV3Response(WxComplaintsReplyRequest replyRequest) throws Exception{
        Integer mchId = complaintsRecordsMapper.getMchIdByComplaintId(replyRequest.getComplaintedId());
        PayConfig payConfig = payConfigMapper.selectByPrimaryKey(mchId);
        WxPayService wxPayService = WxPayServiceUtil.getWxComplaintsV3PayService(payConfig);
        String url = COMPLAINTS_URL + "/" + replyRequest.getComplaintedId()+"/response";
        JSONObject requestJsonObject = new JSONObject();
        requestJsonObject.put("complainted_mchid",payConfig.getMchId());
        requestJsonObject.put("response_content",replyRequest.getResponseContent());
        if (!CollectionUtils.isEmpty(replyRequest.getResponseImages())) {
            requestJsonObject.put("response_images",replyRequest.getResponseImages());
        }
        log.info("查询微信投诉回复用户参数:{}",url);
        JSONObject jsonObject = WxpayV3Util.operationComplaintsV3(url, requestJsonObject,wxPayService.getConfig(),"post");
        //发送回复短信
        sendReplyMsg(replyRequest.getComplaintedId(),null,replyRequest.getResponseContent());

//        log.info("查询微信投诉单回复用户返回:{}",jsonObject.toJSONString());
//        jsonObject.getString("log")
//        saveComplaintsHistory(replyRequest.getComplaintedMchid(),)

        return jsonObject;
    }

    @Override
    public void createComplaints(WxComplaintsCallBackRequest request,WxComplaintsCallBackResponse response) throws Exception {

        WxComplaintsMsgExample example = new WxComplaintsMsgExample();
        example.createCriteria().andComplaintIdEqualTo(response.getComplaint_id());
        List<WxComplaintsMsg> wxComplaintsMsgs = wxComplaintsMsgMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(wxComplaintsMsgs)) {
            //保存投诉通知记录
            WxComplaintsMsg  msg = new WxComplaintsMsg();
            msg.setEventType(request.getEvent_type());
            msg.setSummary(request.getSummary());
            msg.setStatus(1);
            msg.setOutTradeNo(response.getOut_trade_no());
            msg.setComplaintTime(response.getComplaint_time());
            msg.setAmount(response.getAmount());
            msg.setPayerPhone(response.getPayer_phone());
            msg.setComplaintDetail(response.getComplaint_detail());
            msg.setComplaintId(response.getComplaint_id());
            msg.setCreateTime(DateTimeUtil.dealIsoDateToDate(request.getCreate_time()));
            msg.setComplaintMsg(JSONObject.toJSONString(request));
            wxComplaintsMsgMapper.insert(msg);
            //保存投诉单
            ComplaintsRecords records = new ComplaintsRecords();
            records.setComplaintId(response.getComplaint_id());
            records.setAmount(response.getAmount());
            records.setPayerPhone(response.getPayer_phone());
            records.setComplaintDetail(response.getComplaint_detail());

            records.setOutTradeNo(response.getOut_trade_no());
            records.setComplaintTime(response.getComplaint_time());
            records.setOperatorAdminId(1);
            records.setOperatorTime(new Date());
            records.setComplaintState("PENDING");
            records.setComplaintBeginTime(response.getComplaint_time());
            records.setMchId(request.getMch_id());
            ComplaintsOrderResponse complaintsOrderResponse = ordersInfoMapper.queryPlatformData(response.getOut_trade_no());
            if (ObjectUtil.isNotNull(complaintsOrderResponse)) {
                String domain_url = StringUtils.isNotBlank(complaintsOrderResponse.getDomainUrl()) ? "_非支付宝" : "_支付宝渠道";
                records.setPlatformData(complaintsOrderResponse.getOrderSource() + domain_url);
                records.setSupplyProductId(complaintsOrderResponse.getSupplyProductId() != null ? complaintsOrderResponse.getSupplyProductId(): null);
            }
            complaintsRecordsMapper.insert(records);

            //自动回复用户
            WxComplaintsReplyRequest wxComplaintsReplyRequest = new WxComplaintsReplyRequest();
            wxComplaintsReplyRequest.setComplaintedId(response.getComplaint_id());
            wxComplaintsReplyRequest.setResponseContent(autoReplyContent);
            try{
                wxComplaintsV3Response(wxComplaintsReplyRequest);
            }catch (Exception e) {
                log.error("自动回复投诉单失败！！投诉单号:{}",response.getComplaint_id());
                ComplaintsErrorRecords complaintsErrorRecords = new ComplaintsErrorRecords();
                complaintsErrorRecords.setComplaintId(response.getComplaint_id());
                complaintsErrorRecords.setCreateTime(new Date());
                complaintsErrorRecords.setStatus(1);
                complaintsErrorRecords.setOutTradeNo(response.getOut_trade_no());
                complaintsErrorRecords.setType(1);
                complaintsErrorRecordsMapper.insert(complaintsErrorRecords);
            }
            msg.setStatus(2);
            wxComplaintsMsgMapper.updateByPrimaryKey(msg);

            //微信投诉飞书预警
            try{
                String childOrderNo = ordersInfoMapper.queryChildOrderNoByTradeNo(response.getOut_trade_no());
                FeiShuUtil.sendComplaintsMsg(PlatformEnum.getPlatformName(childOrderNo.substring(0,1) )+"  " +response.getComplaint_detail() + "   ,请及时处理");
            }catch (Exception e ) {
                log.error("微信投诉飞书预警失败:{}",e.getMessage());
            }

        }

    }

    private  void sendReplyMsg(String complaintId,String phone,String content){
        WxComplaintsListResponse response = complaintsRecordsMapper.queryComplaintsById(complaintId);
        if (StringUtils.isBlank(phone)) {
            phone = response.getPayerPhone();
        }
        sendComplaintsMsg(phone, content, response.getUserPhone());
    }

    @Override
    public void sendComplaintsMsg(String phone, String content, String userPhone) {
        log.info("发送投诉回复短信参数phone:{}====content:{}=====userPhone:{}",phone,content,userPhone);
        if (StringUtils.isNotBlank(phone)) {
            SmsDto dto = new SmsDto();
            dto.setType(11);
            dto.setPhone(phone);
            dto.setCode(content);
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
            if (!phone.equals(userPhone)) {
                SmsDto dto2 = new SmsDto();
                dto2.setType(11);
                dto2.setPhone(userPhone);
                dto2.setCode(content);
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
            }
        } else {
            SmsDto dto = new SmsDto();
            dto.setType(11);
            dto.setPhone(userPhone);
            dto.setCode(content);
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
        }

    }



    @Override
    public void updateComplaints( WxComplaintsCallBackRequest request,WxComplaintsCallBackResponse response) throws Exception{

        WxComplaintsMsg  msg = new WxComplaintsMsg();
        msg.setEventType(request.getEvent_type());
        msg.setSummary(request.getSummary());
        msg.setStatus(1);
        msg.setOutTradeNo(response.getOut_trade_no());
        msg.setComplaintTime(response.getComplaint_time());
        msg.setAmount(response.getAmount());
        msg.setPayerPhone(response.getPayer_phone());
        msg.setComplaintDetail(response.getComplaint_detail());
        msg.setComplaintId(response.getComplaint_id());
        msg.setCreateTime(DateTimeUtil.dealIsoDateToDate(request.getCreate_time()));
        msg.setComplaintMsg(JSONObject.toJSONString(request));
        wxComplaintsMsgMapper.insert(msg);
        ComplaintsRecords records = complaintsRecordsMapper.queryByComplaintId(response.getComplaint_id());
        if (null !=records) {
            JSONObject jsonObject = queryComplaintsV3(response.getComplaint_id());
            log.info("查询的投诉状态数据是："+ JSON.toJSONString(jsonObject));
            log.info("回调获取的数据是："+ JSON.toJSONString(response));
            //微信投诉飞书预警
            try {
                log.info("原始的投诉单数据是：" + JSON.toJSONString(records));
                Integer currentComplaintTimes = jsonObject.getInteger("user_complaint_times");
                if (records.getUserComplaintTimes() < currentComplaintTimes) {
                    String childOrderNo = ordersInfoMapper.queryChildOrderNoByTradeNo(response.getOut_trade_no());
                    FeiShuUtil.sendComplaintsMsg(PlatformEnum.getPlatformName(childOrderNo.substring(0, 1)) + "(第"+currentComplaintTimes+"+次投诉)  " + response.getComplaint_detail() + "   ,请及时处理");
                }
            } catch (Exception e) {
                log.error("微信投诉飞书预警失败:{}", e.getMessage());
            }
            records.setOperatorAdminId(1);
            records.setOperatorTime(new Date());
            String complaint_state = jsonObject.getString("complaint_state");
            records.setComplaintState(complaint_state);
            records.setUserComplaintTimes(jsonObject.getInteger("user_complaint_times"));
            records.setComplaintDetail(response.getComplaint_detail());
            //用户继续投诉更新投诉开始时间
            records.setComplaintTime(response.getComplaint_time());
            records.setComplaintBeginTime(response.getComplaint_time());
            //自动回复用户
            WxComplaintsReplyRequest wxComplaintsReplyRequest = new WxComplaintsReplyRequest();
            wxComplaintsReplyRequest.setComplaintedId(response.getComplaint_id());
            if ("CONTINUE_COMPLAINT".equals(response.getAction_type())) {
                wxComplaintsReplyRequest.setResponseContent(autoReplyContent);
            } else {
                wxComplaintsReplyRequest.setResponseContent(autoReplyContent2);
            }

            try{
                log.info("微信投诉Complaint_id:{},Action_type:{}",response.getComplaint_id(),response.getAction_type());
                //用户回复才允许自动回复
                if (WxComplaintsStatusEnums.isAutoReply(response.getAction_type())) {
                    wxComplaintsV3Response(wxComplaintsReplyRequest);
                }

            }catch (Exception e) {
                log.error("自动回复投诉单失败！！投诉单号:{}",response.getComplaint_id());
                ComplaintsErrorRecords complaintsErrorRecords = new ComplaintsErrorRecords();
                complaintsErrorRecords.setComplaintId(response.getComplaint_id());
                complaintsErrorRecords.setCreateTime(new Date());
                complaintsErrorRecords.setStatus(1);
                complaintsErrorRecords.setOutTradeNo(response.getOut_trade_no());
                complaintsErrorRecords.setReplyContent(wxComplaintsReplyRequest.getResponseContent());
                complaintsErrorRecordsMapper.insert(complaintsErrorRecords);
            }

            complaintsRecordsMapper.updateByPrimaryKeySelective(records);

        } else {
            records = new ComplaintsRecords();
            JSONObject jsonObject = queryComplaintsV3(response.getComplaint_id());
            records.setComplaintId(response.getComplaint_id());
            records.setAmount(response.getAmount());
            records.setPayerPhone(response.getPayer_phone());
            records.setComplaintDetail(response.getComplaint_detail());
            records.setOutTradeNo(response.getOut_trade_no());
            records.setComplaintTime(response.getComplaint_time());
            records.setComplaintBeginTime(response.getComplaint_time());
            records.setOperatorAdminId(1);
            records.setOperatorTime(new Date());
            String complaint_state = jsonObject.getString("complaint_state");
            records.setComplaintState(complaint_state);
            records.setUserComplaintTimes(jsonObject.getInteger("user_complaint_times"));
            complaintsRecordsMapper.insert(records);

            //微信投诉飞书预警
            try{
                String childOrderNo = ordersInfoMapper.queryChildOrderNoByTradeNo(response.getOut_trade_no());
                FeiShuUtil.sendComplaintsMsg(PlatformEnum.getPlatformName(childOrderNo.substring(0,1) )+"  " +response.getComplaint_detail() + "   ,请及时处理");
            }catch (Exception e ) {
                log.error("微信投诉飞书预警失败:{}",e.getMessage());
            }
        }
        msg.setStatus(2);
        wxComplaintsMsgMapper.updateByPrimaryKey(msg);
    }

    public static void main(String[] args) {
        System.out.println(DateTimeUtil.StrToDate("2024-06-29T19:29:37+08:00"));
    }

}
